package com.spark.gaea.conftk;

import com.google.common.base.Objects;
import com.spark.gaea.config.service.easyzk.ConfigFactory;
import com.spark.gaea.config.service.easyzk.ConfigNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class CTKConfig {
	private Logger LOGGER = LoggerFactory.getLogger(this.getClass());

	public final String ADRESS = "CONFIG_ZK_ADDRESSES";
	public final String NODE = "CONFIG_ZK_NODE";
	public final String MISID = "misid";
	public final String EVN = "EVN";
	@Autowired
	private Environment env;

	public String configZkAddresses() {
		return Objects.firstNonNull(System.getenv("CONFIG_ZK_ADDRESSES"), System.getProperty("CONFIG_ZK_ADDRESSES"));
	}

	public String configZkNode() {
		return Objects.firstNonNull(System.getenv("CONFIG_ZK_NODE"), System.getProperty("CONFIG_ZK_NODE"));
	}

	public String configZkGroup() {
		final String mis = Objects.firstNonNull(System.getenv("misid"), System.getProperty("misid"));
		final String evnString = Objects.firstNonNull(System.getenv("EVN"), System.getProperty("EVN"));
		return evnString + "." + mis;
	}

	public ConfigFactory configFactory() {
		LOGGER.debug("读取环境变量或系统属性以加载远程配置信息");
		return new ConfigFactory(this.configZkAddresses(), this.configZkNode());
	}

	@Bean
	public ConfigNode applicationConfigNode() {
		LOGGER.debug("读取应用环境变量或系统属性以加载远程配置信息");
		final ConfigFactory configFactory = this.configFactory();
		return configFactory.getConfigNode(this.configZkGroup());
	}
}
